<script lang="ts" setup>
import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { auditBusinessMain } from '#/api/per/businessMain'; // 自定义表单 schema

import { useAuditFormSchema } from '../data';

// 父组件触发刷新
const emit = defineEmits<{
  (e: 'success'): void;
}>();

// 表单数据
const formData = ref<{
  busiId: string;
  editFlag: boolean;
  finalAuditStatus: number;
  modifiedData: any;
}>({
  finalAuditStatus: 0,
  busiId: '',
  editFlag: '',
  modifiedData: {},
});

// 标题
const getTitle = computed(() => {
  if (!formData.value) return '';
  switch (formData.value.finalAuditStatus) {
    case 0: {
      return '驳回';
    }
    case 1: {
      return '审核通过';
    }
    case 2: {
      return '审核不通过';
    }
    default: {
      return '审核';
    }
  }
});

// useVbenForm
const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: { class: 'w-full' },
    labelWidth: 100,
  },
  layout: 'horizontal',
  schema: useAuditFormSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) return;

    modalApi.lock();
    try {
      const values = await formApi.getValues();
      await auditBusinessMain({
        ...values,
        finalAuditStatus: formData.value.finalAuditStatus,
        businessId: formData.value.busiId,
        editFlag: formData.value.editFlag,
        modifiedData: formData.value.modifiedData,
      });
      message.success('操作成功');
      emit('success');
      await modalApi.close();
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = { finalAuditStatus: 0, busiId: '' };
      return;
    }
    const data = modalApi.getData<{
      busiId: string;
      finalAuditStatus: number;
    }>();
    formData.value = data;
    await formApi.setValues({});
  },
});
</script>

<template>
  <Modal :title="getTitle" class="w-[50%]">
    <Form class="mx-4" />
  </Modal>
</template>
